package com.knife.blog.web.action;

import java.util.Date;

import javax.servlet.http.Cookie;

import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.BlogUser;
import com.knife.blog.logic.BlogUserService;
import com.knife.blog.logic.impl.ActiveUserImpl;
import com.knife.blog.logic.impl.BlogUserServiceImpl;
import com.knife.util.CommUtil;
import com.knife.util.MD5;
import com.knife.web.ActionContext;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.web.tools.AbstractCmdAction;
import com.knife.web.tools.ActiveUser;

public class BlogLoginAction extends AbstractCmdAction {
	protected BlogUserService userService = BlogUserServiceImpl.getInstance();
	private ActiveUserImpl user;
	
    public Page doInit(WebForm form, Module module) {
    	String url = CommUtil.null2String(form.get("url"));
        if (!"".equals(url)) {
            form.addResult("url", url);
        }
        return module.findPage("login");
    }
    
    public Page doRegister(WebForm form, Module module) {
        return module.findPage("userReg");
    }

    public Page doLogin(WebForm form, Module module) {
        ActionContext.getContext().getSession().removeAttribute("bloguser");
        Page page = null;
        String randomCode = (String) ActionContext.getContext().getSession().getAttribute("rand");
        if (!randomCode.equals((String) form.get("randomCode"))) {
            form.addResult("msg", "验证码不正确，请重新输入！");
            return module.findPage("login");
        }
        user = userService.login(CommUtil.null2String(form.get("username")), CommUtil.null2String(form.get("password")),
                ActionContext.getContext().getRequest().getRemoteAddr());
        if (user != null) {
            BlogInfo bloginfo = userService.getUserBlog("username", CommUtil.null2String(form.get("username")));
            if (bloginfo == null) {
                form.addResult("msg", "您的博客注册失败，请重新注册");
                userService.delUserInfo(CommUtil.null2String(form.get("username")));
                page = module.findPage("login");
                return page;
            }
            if (user.getStatus() == 0) {
                form.addResult("msg", "您的博客还在审核中，请耐心等待");
                page = module.findPage("login");
                return page;
            }
            ActionContext.getContext().getSession().setAttribute("bloguser",user);// 登录标志
            // page = module.findPage("loginSuccess");
            String url = CommUtil.null2String(form.get("url"));
            if ("".equals(url)) {
                url = "/manage.do";
            }
            form.addResult("js", "top.location.replace('" + url + "');");
            form.addResult("username", user.getUserName());
            ActionContext.getContext().getSession().setAttribute("username", user.getUserName());
            page = new Page("index", "/manage/javascript.html", "template");
        } else {
            form.addResult("msg", "用户名或者密码不正确，请重新输入！");
            page = module.findPage("login");
        }
        return page;
    }

    public Page doSaveUserReg(WebForm form, Module module) {
        String username = CommUtil.null2String(form.get("username"));
        String password = CommUtil.null2String(form.get("password"));
        String password1 = CommUtil.null2String(form.get("password1"));
        if (username.equals("") || password.equals("")) {
            form.addResult("msg", "用户名及密码不能为空！");
            return module.findPage("userReg");
        }
        if (!password.equals(password1)) {
            form.addResult("msg", "两次输入的密码不相同！");
            return module.findPage("userReg");
        }
        BlogUser user = new BlogUser();
        user.setUsername(username);
        user.setPassword(MD5.encode(CommUtil.null2String(form.get("password"))));
        user.setEmail(CommUtil.null2String(form.get("email")));
        user.setSex(CommUtil.null2String(form.get("sex")));
        user.setTel(CommUtil.null2String(form.get("tel")));
        user.setQq(CommUtil.null2String(form.get("qq")));
        user.setIntro(CommUtil.null2String(form.get("intro")));
        user.setInputtime(new Date());
        user.setStatus(0);
        user.setTagimg(CommUtil.null2String(form.get("tagimg")));
        if (userService.getBlogUser(username) != null) {
            form.addResult("msg", "用户名已经存在！");
            System.out.println("用户名已经存在！");
            return module.findPage("userReg");
        }
        if (userService.add(user)) {
            form.addResult("msg", "用户信息设置成功，请继续设置博客信息！");
            System.out.println("用户信息设置成功，请继续设置博客信息！");
            ActiveUser actUser = userService.login(username, MD5.encode(password),
                    "0", ActionContext.getContext().getRequest().getRemoteAddr());
            /*MessageUtil.sendSystemMessage(WebMessage.WELCOMEMSG, userInfo
            .getUserName());*/
            if (actUser != null) {
                ActionContext.getContext().getSession().setAttribute("bbsuser",
                        actUser);// 登录标志
                // return module.findPage("loginSuccess");
                //form.addResult("js", "top.location.href('');");
                //return new Page("index", "/manage/javascript.html", "template");
            }
            return module.findPage("register");
        } else {
            form.addResult("msg", "用户信息设置失败！");
            return module.findPage("userReg");
        }
    }

    public Page doSaveRegister(WebForm form, Module module) {
        BlogInfo info;
        info = (BlogInfo) form2Obj(form);
        info.setUpdated(Boolean.TRUE);
        info.setFirtpagenum(10);
        info.setListnum(10);
        info.setManagelistnum(10);
        info.setNewmessagenum(10);
        info.setTopreadnum(10);
        info.setTopreviewnum(10);

        info.setType("userBlog");
        String imgurl = "/images/default.gif";
        info.setTagimg(imgurl);
        BlogUser blogUser = userService.getBlogUser(info.getUsername());
        if (!info.getUsername().equals("admin")) {
            info.setStatus(0);
            blogUser.setStatus(0);
        } else {
            info.setStatus(1);
            blogUser.setStatus(0);
        }
        userService.updateUserInfo(blogUser);
        boolean ret = userService.register(info);
        if (ret) {
            //HTMLGenerater.saveMessageToHTML(blog);
            form.addResult("msg", "注册成功，请等待我们审核!");
            return module.findPage("register");
            //Page indexPage=new Page("index","blog.do","html");
            //indexPage.
            //return new Page("index", "/blog.do", "html");
        } else {
            form.addResult("msg", "域名已经存在！");
            System.out.println("域名已经存在！");
            return module.findPage("register");
        }
    }

    public Page doShowLogin(WebForm form, Module module) {
        ActionContext.getContext().getSession().removeAttribute("bloguser");
        ActionContext.getContext().getSession().removeAttribute("isAdmin");
        ActionContext.getContext().getSession().invalidate();//清空session
        Cookie cookie = ActionContext.getContext().getRequest().getCookies()[0];//获取cookie
        cookie.setMaxAge(0);//让cookie过期
        return module.findPage("login");
    }
    
    public Page doLogout(WebForm form, Module module) {
        ActionContext.getContext().getSession().removeAttribute("bloguser");
        ActionContext.getContext().getSession().removeAttribute("isAdmin");
        ActionContext.getContext().getSession().removeAttribute("bloguser");
        ActionContext.getContext().getSession().removeAttribute("isAdmin");
        ActionContext.getContext().getSession().invalidate();//清空session
        Cookie cookie = ActionContext.getContext().getRequest().getCookies()[0];//获取cookie
        cookie.setMaxAge(0);//让cookie过期
        form.addResult("url", "/blog.do");
        //return new Page("clientforward", "/index.htm", "html");
        return module.findPage("login");
    }
    
    public Object form2Obj(WebForm form) {
        String cid = CommUtil.null2String(form.get("cid"));
        BlogInfo obj = userService.getBlogInfo(cid);
        if (obj == null) {
            obj = new BlogInfo();
        }
        // 此处需要修改，妨止系统字段被从外面非法赋值
        form.toPo(obj);
        return obj;
    }
	
}
